let app = getApp()
import { request } from "../../utils/request.js";

Page({
    data: {
        categoryConditionList: [],
        conditionList: [],
        pop_show: false,
        pop_show_to: false,
        chooseGroupList: [{
            groupId: wx.getStorageSync('userInfo').groupVO.id,
            groupName: wx.getStorageSync('userInfo').groupVO.name,
            type: "#deb13c"
        }],
        chooseGroupIdList: ["" + wx.getStorageSync('userInfo').groupVO.id],
        groupColorList: ["#deb13c", "#0eb13c", "#b924c7"],
        allGroupList: [],
        showChooseGroupPopup: false,
        currentDate: new Date().getTime(),
        maxDate: new Date().getTime(),
        earlyMonthDate: "",
        minDate: 0,
        year: '',
        month: '',
        day: '',
        toYear: '',
        toMonth: '',
        toDay: '',
        searchKey: '',
        statusBarHeight: app.globalData.statusBarHeight,
        navBarHeight: app.globalData.navBarHeight,
        configColor: app.globalData.configColor,
        ColorLess: app.globalData.ColorLess,
        ColorMost: app.globalData.ColorMost,
        billPart: 0,
        billList: [],
        billTempList: [],
        idList: [],
        idTempList: [],
        parentIdList: [],
        parentIdTempList: [],
        outcome: 0,
        income: 0,
        jieyu: 0,
        isOnLoad: false,
        showUser: false,
        showGroupColor: true,
        detail_show: false,
        selectedGroupName: '',
        selectedCategoryName: '',
        selectedMoney: '',
        selectedDate: '',
        selectedRemark: '',
        selectedUserName: '',
        quickChooseDateList: ['本周', '上周', '本周+上周', '本月', '上月', '本月+上月', '最近7天', '最近14天'],
        allCategory: [],
        showQuickDate: false,
        showCategory: false,
        showHalves: false,
        agvMoney: 0,
        totalPerson: 0,
        transferList: [],
        isAllChecked: false,
        showAgvRemaining: false,
        agvType: '',
        diffCount: 0,
        agvForDate: null,
        isAllGroupUser: false,
        showAllGroupUser: true,
    },
    changeIsAllGroupUser() {
        this.setData({
            isAllGroupUser: !this.data.isAllGroupUser
        })
        this.showHalves(1)
    },
    async showAgvRemaining(e) {
        this.onClose()
        if (this.data.billPart != 0) {
            wx.showToast({
                title: '请勾选全部!',
                icon: 'error'
            })
            return
        }
        let fromDate = new Date(this.data.year, this.data.month - 1, this.data.day);
        let toDate = new Date(this.data.toYear, this.data.toMonth - 1, this.data.toDay);
        let today = new Date(this.data.maxDate);
        today.setHours(0, 0, 0, 0);
        fromDate.setHours(0, 0, 0, 0);
        toDate.setHours(0, 0, 0, 0);
        let diffCount = 0
        if (e.currentTarget.dataset.type == '周') {
            if (fromDate.getDay() != 1) {
                const day = fromDate.getDay(); // 0是周日，1是周一...6是周六
                // 计算最近的周一
                const monday = new Date(fromDate);
                if (day >= 2 && day <= 4) { // 周二到周四
                    monday.setDate(fromDate.getDate() - (day - 1)); // 直接回溯到本周一
                } else { // 周五到周日（0=周日）
                    const daysToAdd = day === 0 ? 1 : 8 - day; // 周日加1天，周五/六加对应天数
                    monday.setDate(fromDate.getDate() + daysToAdd);
                }
                // 确保不超过今天
                fromDate = monday > today ?
                    fromDate.setDate(today.getDate() - today.getDay() + (today.getDay() === 0 ? -6 : 1)) :
                    monday;
            }
            if (toDate.getDay() != 0) {
                const day = toDate.getDay(); // 0是周日，1是周一...6是周六
                if (day >= 1 && day <= 3) {
                    toDate.setDate(toDate.getDate() - day);
                } else {
                    toDate.setDate(toDate.getDate() + (7 - day));
                }
                // 确保不超过今天
                if (toDate > today) {
                    toDate.setDate(today.getDate() - today.getDay())
                }
            }
            if (toDate < fromDate) {
                fromDate.setDate(fromDate.getDate() - 7)
            }
            diffCount = Math.floor(Math.abs(toDate - fromDate) / (1000 * 60 * 60 * 24 * 7)) + 1
        }
        if (e.currentTarget.dataset.type == '月') {
            const nextDay = new Date(toDate);
            nextDay.setDate(toDate.getDate() + 1);
            if (fromDate.getDate() != 1) {
                const dateForMonth = fromDate.getDate();
                if (dateForMonth >= 2 && dateForMonth <= 15) {
                    fromDate.setDate(fromDate.getDate() - (dateForMonth - 1));
                } else {
                    if (fromDate.getMonth() === 11) {
                        fromDate = new Date(fromDate.getFullYear() + 1, 0, 1);
                    } else {
                        fromDate = new Date(fromDate.getFullYear(), fromDate.getMonth() + 1, 1);
                    }
                }
            }
            if (nextDay.getMonth() == toDate.getMonth()) {
                const dateForMonth = toDate.getDate();
                if (dateForMonth >= 1 && dateForMonth <= 15) {
                    if (toDate.getMonth() === 0) {
                        toDate = new Date(toDate.getFullYear() - 1, 11, 31);
                    } else {
                        // 常规情况：当前月份设为0（上月最后一天）
                        toDate = new Date(toDate.getFullYear(), toDate.getMonth(), 0);
                    }
                } else {
                    toDate = new Date(toDate.getFullYear(), toDate.getMonth() + 1, 0);
                    if (toDate > today) {
                        toDate = new Date(toDate.getFullYear(), toDate.getMonth(), 0);
                    }
                }
            }
            if (toDate < fromDate) {
                fromDate = new Date(fromDate.getFullYear(), fromDate.getMonth() - 1, 1);
            }
            diffCount = (this.data.toYear - this.data.year) * 12 + (this.data.toMonth - this.data.month) + 1
        }
        if (fromDate.getFullYear() != this.data.year
            || fromDate.getMonth() + 1 != this.data.month
            || fromDate.getDate() != this.data.day
            || toDate.getFullYear() != this.data.toYear
            || toDate.getMonth() + 1 != this.data.toMonth
            || toDate.getDate() != this.data.toDay) {
            this.setData({
                agvType: e.currentTarget.dataset.type,
                diffCount: diffCount,
                year: fromDate.getFullYear(),
                month: fromDate.getMonth() + 1,
                day: fromDate.getDate(),
                toYear: toDate.getFullYear(),
                toMonth: toDate.getMonth() + 1,
                toDay: toDate.getDate(),
            })
            await this.show()
        }
        wx.request({
            url: app.globalData.url + '/agvRemaining',
            method: 'POST',
            header: { 'content-type': 'application/json' },
            data: {
                idList: this.data.idTempList,
                agvType: e.currentTarget.dataset.type,
                monthCount: diffCount
            },
            success: (res) => {
                let data = res.data.data
                this.setData({
                    showAgvRemaining: true,
                    agvForDate: data,
                    isAllChecked: this.data.idTempList.length == this.data.idList.length
                })
                wx.hideLoading()
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })
    },
    // 平摊费用
    showHalves(temp) {
        if (temp != 1) {
            this.onClose()
        }
        if (this.data.billPart != -1) {
            wx.showToast({
                title: '请勾选支出!',
                icon: 'error'
            })
            return
        }
        wx.showLoading({
            title: '计算中...',
        })
        // 平摊费用
        wx.request({
            url: app.globalData.url + '/equalShares',
            method: 'POST',
            header: { 'content-type': 'application/json' },
            data: {
                groupIdList: this.data.chooseGroupIdList,
                idList: this.data.idTempList,
                isAllGroupUser: this.data.isAllGroupUser
            },
            success: (res) => {
                let data = res.data.data
                this.setData({
                    showAllGroupUser: data.showAllGroupUser,
                    agvMoney: data.agvMoney,
                    money: data.money,
                    totalPerson: data.billVOList.length,
                    transferList: data.billVOList,
                    isAllChecked: this.data.idTempList.length == this.data.idList.length,
                    showHalves: true
                })
                wx.hideLoading()
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })
    },
    // 删除某个分类条件
    closeCategoryCondition(e) {
        let array = this.data.categoryConditionList
        let index = e.currentTarget.dataset.index
        array.splice(index, 1);
        this.setData({
            categoryConditionList: array
        })
        this.show()
    },
    chooseCategory(e) {
        let categroy = e.currentTarget.dataset.choose
        let categoryConditionList = this.data.categoryConditionList
        const isSomeChecked = categoryConditionList.some(item => item == categroy.name);
        if (!isSomeChecked) {
            categoryConditionList.push(categroy.name)
            this.setData({
                categoryConditionList: categoryConditionList
            })
            this.show()
        }
    },
    showCategory() {
        this.onClose()
        this.setData({
            showCategory: true
        })
    },
    // 展示快选日期
    showQuickDate() {
        this.onClose()
        this.setData({
            showQuickDate: true
        })
    },
    // 选择快选日期
    chooseQuickDate(e) {
        let fromDate = new Date();
        let toDate = new Date();
        switch (e.currentTarget.dataset.choose) {
            case 0:
                // 本周
                const difference = fromDate.getDate() - fromDate.getDay() + (fromDate.getDay() === 0 ? -6 : 1);
                fromDate.setDate(difference);
                break
            case 1:
                // 上周               
                // 计算上周一的日期
                fromDate.setDate(fromDate.getDate() - fromDate.getDay() - 6);
                // 计算上周日的日期
                toDate.setDate(fromDate.getDate() + 6);
                break
            case 2:
                // 本周+上周
                // 上周
                // 计算上周一的日期
                fromDate.setDate(fromDate.getDate() - fromDate.getDay() - 6);
                break
            case 3:
                // 本月
                fromDate.setDate(1)
                break
            case 4:
                // 上月
                fromDate = new Date(fromDate.getFullYear(), fromDate.getMonth() - 1, 1);
                toDate = new Date(toDate.getFullYear(), toDate.getMonth(), 0);
                break
            case 5:
                // 本月+上月
                fromDate = new Date(fromDate.getFullYear(), fromDate.getMonth() - 1, 1);
                break
            case 6:
                // 最近7天
                fromDate.setDate(fromDate.getDate() - 6)
                break
            case 7:
                // 最近14天
                fromDate.setDate(fromDate.getDate() - 13)
                break
        }
        if (toDate.getTime() > this.data.maxDate) {
            toDate = new Date(this.data.maxDate)
        }
        if (fromDate.getTime() > this.data.maxDate) {
            fromDate = new Date(this.data.maxDate)
        }
        if (toDate.getTime() < this.data.minDate) {
            toDate = new Date(this.data.minDate)
        }
        if (fromDate.getTime() < this.data.minDate) {
            fromDate = new Date(this.data.minDate)
        }
        this.setData({
            showQuickDate: false,
            year: fromDate.getFullYear(),
            month: fromDate.getMonth() + 1,
            day: fromDate.getDate(),
            toYear: toDate.getFullYear(),
            toMonth: toDate.getMonth() + 1,
            toDay: toDate.getDate(),
            earlyMonthDate: fromDate.getTime(),
            currentDate: toDate.getTime(),
        })
        this.show()
    },
    // 一键反选
    invert() {
        this.onClose()
        let idList = [...this.data.idList];
        let idTempList = [...this.data.idTempList];
        let parentIdList = [...this.data.parentIdList];
        idTempList = idList.filter(item => !idTempList.includes(item));
        let parentIdTempSet = new Set()
        idTempList.forEach(id => {
            parentIdList.forEach(pId => {
                if (pId.includes(id)) {
                    parentIdTempSet.add(pId)
                }
            })
        })
        const parentIdTempList = [...parentIdTempSet];
        let billList = [...this.data.billList];
        billList.forEach(billForDay => {
            let outForDay = 0
            let inForDay = 0
            billForDay.billVOList.forEach(function (record) {
                record.checked = !record.checked
                if (record.checked) {
                    if (record.isOut) {
                        outForDay = Number((outForDay + record.money).toFixed(2))
                    } else {
                        inForDay = Number((inForDay + record.money).toFixed(2))
                    }
                }
            })
            // 重算当日收支
            let remainForDay = Number((inForDay - outForDay).toFixed(2));
            billForDay.inForDay = inForDay;
            billForDay.outForDay = outForDay;
            billForDay.remainForDay = remainForDay;

            const isSomeChecked = billForDay.billVOList.some(item => item.checked);
            const isAllNotChecked = billForDay.billVOList.every(item => !item.checked);
            if (isSomeChecked) {
                billForDay.checked = true
            }
            if (isAllNotChecked) {
                billForDay.checked = false
            }
        })
        // 重算月收支
        let outForMonth = 0
        let inForMonth = 0
        billList.forEach(item => {
            outForMonth = Number((outForMonth + item.outForDay).toFixed(2))
            inForMonth = Number((inForMonth + item.inForDay).toFixed(2))
        })
        this.setData({
            idTempList,
            parentIdTempList,
            billList,
            outcome: outForMonth,
            income: inForMonth,
            jieyu: (inForMonth - outForMonth).toFixed(2),
        })
    },
    // 勾选框有变化
    checkboxChange(e) {
        let arraySet = new Set(e.detail.value)
        let parentIdSet = [...arraySet].filter(item => item.startsWith('f'));
        let idSet = [...arraySet].filter(item => !item.startsWith('f'));

        let optIdList = [];
        let idTempList = [...this.data.idTempList];
        if (idSet.length > idTempList.length) {
            optIdList = [...idSet].filter(item => !idTempList.includes(item));
            idTempList = [...idTempList, ...optIdList];
        } else if (idSet.length < idTempList.length) {
            optIdList = idTempList.filter(item => !arraySet.has(item));
            idTempList = idTempList.filter(item => !optIdList.includes(item));
        }

        let optParentIdList = [];
        let parentIdTempList = [...this.data.parentIdTempList];
        if (parentIdSet.length > parentIdTempList.length) {
            optParentIdList = [...parentIdSet].filter(item => !parentIdTempList.includes(item));
            parentIdTempList = [...parentIdTempList, ...optParentIdList];
        } else if (parentIdSet.length < parentIdTempList.length) {
            optParentIdList = parentIdTempList.filter(item => !arraySet.has(item));
            parentIdTempList = parentIdTempList.filter(item => !optParentIdList.includes(item));
        }

        if (optParentIdList.length > 0) {
            const parentBillList = this.data.billList.filter(item => optParentIdList.includes(item.parentId))
            parentBillList[0].checked = !parentBillList[0].checked
            let outForDay = 0
            let inForDay = 0
            parentBillList[0].billVOList.forEach(function (record) {
                record.checked = parentBillList[0].checked
                if (record.checked) {
                    idTempList.push(record.id + "")
                    if (record.isOut) {
                        outForDay = Number((outForDay + record.money).toFixed(2))
                    } else {
                        inForDay = Number((inForDay + record.money).toFixed(2))
                    }
                } else {
                    idTempList = idTempList.filter(item => item != record.id);
                }
            });
            // 重算当日收支
            let remainForDay = (inForDay - outForDay).toFixed(2);
            parentBillList[0].inForDay = inForDay;
            parentBillList[0].outForDay = outForDay;
            parentBillList[0].remainForDay = remainForDay;
        }
        if (optIdList.length > 0) {
            const parentIdList = this.data.parentIdList.filter(parentId => parentId.includes(optIdList[0]))
            const parentBillList = this.data.billList.filter(item => parentIdList[0] == item.parentId)
            let outForDay = 0
            let inForDay = 0
            parentBillList[0].billVOList.forEach(function (record) {
                if (record.id == optIdList[0]) {
                    record.checked = !record.checked
                }
                if (record.checked) {
                    if (record.isOut) {
                        outForDay = Number((outForDay + record.money).toFixed(2))
                    } else {
                        inForDay = Number((inForDay + record.money).toFixed(2))
                    }
                }
            });
            // 重算当日收支
            let remainForDay = (inForDay - outForDay).toFixed(2);
            parentBillList[0].inForDay = inForDay;
            parentBillList[0].outForDay = outForDay;
            parentBillList[0].remainForDay = remainForDay;

            const isSomeChecked = parentBillList[0].billVOList.some(item => item.checked);
            const isAllNotChecked = parentBillList[0].billVOList.every(item => !item.checked);
            if (isSomeChecked) {
                parentBillList[0].checked = true
                parentIdTempList.push(parentBillList[0].parentId + "")
            }
            if (isAllNotChecked) {
                parentBillList[0].checked = false
                parentIdTempList = parentIdTempList.filter(item => item != parentBillList[0].parentId);
            }
        }
        // 重算月收支
        let outForMonth = 0
        let inForMonth = 0
        this.data.billList.forEach(item => {
            outForMonth = Number((outForMonth + item.outForDay).toFixed(2))
            inForMonth = Number((inForMonth + item.inForDay).toFixed(2))
        })
        // 最后更新数据
        this.setData({
            idTempList,
            parentIdTempList,
            billList: this.data.billList,
            outcome: outForMonth,
            income: inForMonth,
            jieyu: (inForMonth - outForMonth).toFixed(2),
        })
    },
    // 关闭弹出
    onClose() {
        this.setData({
            showAgvRemaining: false,
            showHalves: false,
            showCategory: false,
            showChooseGroupPopup: false,
            pop_show: false,
            pop_show_to: false,
            showQuickDate: false,
            detail_show: false,
            selectedGroupName: '',
            selectedMoney: '',
            selectedDate: '',
            selectedRemark: '',
            selectedUserName: '',
            agvMoney: '',
            money: '',
            totalPerson: '',
            transferList: []
        });
    },
    // 账本
    openChooseGroupPopup() {
        this.onClose()
        if (this.data.chooseGroupList.length == 3) {
            wx.showToast({
                title: '最多选择三个账本',
                icon: 'error'
            })
            return
        }
        // 查找所有账本
        wx.request({
            url: app.globalData.url + '/group',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id
            },
            success: (res => {
                let responseData = res.data
                let reslut = []
                if (responseData.flag) {
                    responseData.data.forEach(function (item) {
                        if (item.active == 2) {
                            reslut.push(item)
                        }
                    });
                    this.setData({
                        allGroupList: reslut
                    })
                }
            })
        })
        this.setData({
            showChooseGroupPopup: true
        })
    },
    async onChangeChooseGroup(event) {
        if (event.detail.length == 0) {
            wx.showToast({
                title: '至少选择一个账本',
                icon: 'error'
            })
            return
        }
        this.setData({
            chooseGroupIdList: event.detail,
        });
        let newChooseGroupList = []
        for (let i = 0; i < this.data.chooseGroupIdList.length; i++) {
            for (let j = 0; j < this.data.allGroupList.length; j++) {
                if (this.data.allGroupList[j].id == this.data.chooseGroupIdList[i]) {
                    newChooseGroupList.push({
                        groupId: this.data.allGroupList[j].id,
                        groupName: this.data.allGroupList[j].name,
                        type: this.data.groupColorList[i]
                    })
                }
            }
        }
        this.setData({
            chooseGroupList: newChooseGroupList,
        });
        await this.getDateRangeByGroup()
        this.show()
    },
    async clickOneGroup(event) {
        const { groupid } = event.currentTarget.dataset;
        const checkbox = this.selectComponent(`.checkboxes-${groupid}`);
        checkbox.toggle();
        await this.getDateRangeByGroup()
        this.show()
    },
    async closeOneGroupTag(e) {
        if (this.data.chooseGroupList.length == 1) {
            wx.showToast({
                title: '至少选择一个账本',
                icon: 'error'
            })
            return
        }
        let removeGroupId = e.currentTarget.dataset.groupid;
        let newChooseGroupIdList = this.data.chooseGroupIdList.filter(item => item !== removeGroupId);
        this.setData({
            chooseGroupIdList: newChooseGroupIdList
        })
        let newChooseGroupList = this.data.chooseGroupList.filter(item => item.groupId !== removeGroupId);
        this.setData({
            chooseGroupList: newChooseGroupList
        })
        const checkbox = this.selectComponent(`.checkboxes-${removeGroupId}`);
        checkbox.toggle();
        await this.getDateRangeByGroup()
        this.show()
    },
    // 支出/收入/全部 单选
    changeChecked(e) {
        this.setData({
            billPart: e.detail.value
        })
        this.show()
    },
    // 展示记录人
    isShowUser(e) {
        this.setData({
            showUser: !this.data.showUser
        })
    },
    // 展示账本颜色
    isShowGroupColor(e) {
        this.setData({
            showGroupColor: !this.data.showGroupColor
        })
    },
    // 开启时间选择弹窗
    showTimeChoosePopup(e) {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        this.onClose()
        if (e.currentTarget.dataset.isto == "0") {
            this.setData({
                pop_show: true,
            });
        } else {
            this.setData({
                pop_show_to: true,
            });
        }
    },
    // 年月选择
    chooseDate(event) {
        this.onClose()
        let date = new Date(event.detail);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        if (this.data.dateCategroy != '单月') {
            if (year > this.data.toYear || (year == this.data.toYear && month > this.data.toMonth)) {
                wx.showToast({
                    title: '请选择正确时间',
                    icon: 'none'
                })
                return
            }
        }
        this.setData({
            pop_show: false,
            year: year,
            month: month,
            day: day
        })
        this.show()
    },
    chooseDateTo(event) {
        this.onClose()
        let date = new Date(event.detail);
        let toYear = date.getFullYear();
        let toMonth = date.getMonth() + 1;
        let toDay = date.getDate();
        if (this.data.year > toYear || (this.data.year == toYear && this.data.month > toMonth)) {
            wx.showToast({
                title: '请选择正确时间',
                icon: 'none'
            })
            return
        }
        this.setData({
            pop_show_to: false,
            toYear: date.getFullYear(),
            toMonth: date.getMonth() + 1,
            toDay: toDay
        })
        this.show()
    },
    // 删除某个条件
    closeCondition(e) {
        let array = this.data.conditionList
        let index = e.currentTarget.dataset.index
        array.splice(index, 1);
        this.setData({
            conditionList: array
        })
        this.show()
    },
    // 搜索框确认搜索
    onSearchConfirm(event) {
        let keyCode = event.detail.value.trim()
        if (keyCode.length === 0) {
            return
        }
        let conditionList = this.data.conditionList
        if (conditionList.length > 5) {
            wx.showToast({
                title: '最多搜索6个关键词',
                icon: 'none'
            })
            return
        }
        conditionList.push(keyCode)
        this.setData({
            conditionList: conditionList,
            searchKey: ""
        })
        this.show()
    },
    // 单条详情
    onTapAndOpenDetail(e) {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        let detail = e.currentTarget.dataset.detail
        this.data.chooseGroupList.forEach(element => {
            if (element.groupId == detail.groupId) {
                detail.groupName = element.groupName
            }
        });
        let money = ''
        if (detail.isOut) {
            money = detail.money + ' (支出)'
        } else {
            money = detail.money + ' (收入)'
        }
        this.setData({
            detail_show: true,
            selectedGroupName: detail.groupName,
            selectedCategoryName: detail.categoryName,
            selectedMoney: money,
            selectedDate: detail.createTime,
            selectedRemark: detail.remark,
            selectedUserName: detail.username,
        })
    },
    async getDateRangeByGroup() {
        // 获取最早+最晚记录时间
        const dateRangeData = await request({
            url: "/getDateRangeByGroup",
            method: "POST",
            header: { 'content-type': 'application/json' },
            data: { groupIdList: this.data.chooseGroupIdList }
        })
        var date;
        if (dateRangeData.maxDateStamp == null) {
            date = new Date();
        } else {
            date = new Date(dateRangeData.maxDateStamp);
        }
        this.setData({
            minDate: dateRangeData.minDateStamp,
            maxDate: dateRangeData.maxDateStamp,
            year: date.getFullYear(),
            month: date.getMonth() + 1,
            day: 1,
            toYear: date.getFullYear(),
            toMonth: date.getMonth() + 1,
            toDay: date.getDate(),
            currentDate: dateRangeData.maxDateStamp,
        })
        date.setDate(1);
        this.setData({
            earlyMonthDate: date.getTime(),
        })
    },
    async show() {
        wx.showLoading({
            title: '计算中...',
        })
        // 获取账单
        const data = await request({
            url: "/getBillByDetailedParam",
            method: "POST",
            header: { 'content-type': 'application/json' },
            data: {
                userId: wx.getStorageSync('userInfo').id,
                conditionList: this.data.conditionList,
                groupIdList: this.data.chooseGroupIdList,
                year: this.data.year,
                month: this.data.month,
                day: this.data.day,
                toYear: this.data.toYear,
                toMonth: this.data.toMonth,
                toDay: this.data.toDay,
                billPart: this.data.billPart,
                categoryNameList: this.data.categoryConditionList,
                showHalves: this.data.showHalves
            }
        })
        data.forEach(billForDay => {
            billForDay.billVOList.forEach(record => {
                for (let index = 0; index < this.data.chooseGroupList.length; index++) {
                    const chooseGroup = this.data.chooseGroupList[index];
                    if (chooseGroup.groupId == record.groupId) {
                        record.backgroundColor = chooseGroup.type + "1f"
                        break
                    }
                }
            });
        });
        this.setData({
            billList: data,
            billTempList: data,
            outcome: 0,
            income: 0,
            jieyu: 0,
            idList: [],
            idTempList: [],
            parentIdList: [],
            parentIdTempList: [],
        })
        if (data.length > 0) {
            this.setData({
                idList: data[0].idList,
                idTempList: data[0].idList,
                parentIdList: data[0].parentIdList,
                parentIdTempList: data[0].parentIdList,
                outcome: data[0].outForMonth,
                income: data[0].inForMonth,
                jieyu: data[0].remainForMonth,
            })
        }
        // 获取当前账单的所有类别
        const allCategory = await request({
            url: "/getBillAllCategory",
            method: "POST",
            header: { 'content-type': 'application/json' },
            data: {
                userId: wx.getStorageSync('userInfo').id,
                day: this.data.day,
                year: this.data.year,
                month: this.data.month,
                toYear: this.data.toYear,
                toMonth: this.data.toMonth,
                toDay: this.data.toDay,
                groupIdList: this.data.chooseGroupIdList
            }
        })
        this.setData({
            allCategory: allCategory,
        })
        wx.hideLoading()
    },
    onLoad: function (options) {
        this.getDateRangeByGroup().then(() => {
            this.show()
            this.setData({
                isOnLoad: true
            })
        });
    },
    onShow: function () {
        // 登录弹窗
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        // 切换主题颜色
        if (wx.getStorageSync('configColor') !== this.data.configColor
            || wx.getStorageSync('ColorLess') !== this.data.ColorLess
            || wx.getStorageSync('ColorMost') !== this.data.ColorMost) {
            this.setData({ configColor: wx.getStorageSync('configColor') });
            this.setData({ ColorLess: wx.getStorageSync('ColorLess') });
            this.setData({ ColorMost: wx.getStorageSync('ColorLColorMostess') });
        }
        this.onClose()
        if (!this.data.isOnLoad) {
            return
        }
        this.show()
    }

})



